//
//  XHHomeTableViewController.swift
//  gu-新浪微博
//
//  Created by xiaohui on 16/6/25.
//  Copyright © 2016年 gusheghui. All rights reserved.
//

import UIKit
import AFNetworking

private let statusCellId = "statusCellId"
let Margin: CGFloat = 10
class XHHomeTableViewController: XHVisitorTableViewController {
    
    let refresh = UIRefreshControl()
    
    var statusArray:[XHStatus] = [XHStatus]()
    override func viewDidLoad() {
        super.viewDidLoad()

        
        
        if !isLogin{
            visitorView?.setupVistorViewInfo(nil, title: nil)
            return
        }
        loadSatusData(indicatorView.isAnimating())
        setupTableViewInfo()
 
    }
    
        //设置tableView的相关属性
    
    func setupTableViewInfo(){
        
        tableView.registerClass(XHStautsCell.self, forCellReuseIdentifier: statusCellId)
        
        //cell高度  // 自动计算行高 ,并预估行高 并要设置cell的约束
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        //取消分割线
        tableView.separatorStyle = .None
        
        tableView.tableFooterView = indicatorView
        
        loadSatusData(indicatorView.isAnimating())
        
        tableView.addSubview(refresh)
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
        
        
    }
    //开始刷新
    @objc private func refreshAction(){
    
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), {() -> Void in
            
            
        });
        
        
    }
    //结束刷新
    func endRefresh(){
        
    }
    
//    UIActivityIndicatorView
    //设置加载控件
    private lazy var indicatorView : UIActivityIndicatorView = {
       let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.blueColor()
        view.backgroundColor = UIColor.yellowColor()
        return view
    }()
//    indicatorView.isAnimating()
}
extension XHHomeTableViewController{
 
    func loadSatusData(pullUp:Bool){
        //    since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。 下拉刷新
        //    max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0 上拉加载更多
        
       
        var maxId:Int64 = 0
        var sinceId:Int64 = 0
        if pullUp{
            
            maxId = statusArray.last?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }else{
                
                sinceId = statusArray.first?.id ?? 0
            }
            
            
        }
        


        XHNetworkTools.sharedTools.homeLoadStatusData(sinceId, maxId: maxId, success: { (response) -> () in
            self.indicatorView.stopAnimating()
            
            guard let res = response?["statuses"] as?[[String: AnyObject]] else {
                
                return
            }
            var tempArray:[XHStatus] = [XHStatus]()
            
            
            for dic in res{
                let status = XHStatus(dict: dic)
                //保存模型
                tempArray.append(status)
                
            }
            
            self.statusArray = tempArray
            
            if pullUp{
                self.statusArray = self.statusArray + tempArray
            }else{
                self.statusArray = tempArray + self.statusArray
            }
            
            
            self.tableView.reloadData()
            }) { (error) -> () in
                print("错误是\(error)")
                
        }
    }
}
//数据源方法

extension XHHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusArray.count
//        return 20
       
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellId, forIndexPath: indexPath) as! XHStautsCell
        
        cell.status = statusArray[indexPath.row]
//        print(statusArray.count)
        
        return cell
    }
  
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if statusArray.count == indexPath.row + 1 {
            //开启动画
            indicatorView.startAnimating()
            
            loadSatusData(indicatorView.isAnimating())
        }
//        print(indexPath.row)
    }
    
}


